if(mui.os.plus) {
	mui.plusReady(function() {
		init();
	})
} else {
	init();
}

function init() {
	function AppCtrl($scope, $sce) {
		$scope.setProject = function(id) {
			$scope.currentProject = $scope.projects[id];
			$scope.currentProjectUrl = $sce.trustAsResourceUrl($scope.currentProject.url);
		}
	}
	//转换歌词方法
	function HtmlDecode(str) {
		var t = document.createElement("div");
		t.innerHTML = str;
		return t.textContent || t.innerText;
	}
	//将时间转换成秒
	function tranToSec(time) {
		if(time && typeof time == "string") {
			var arr = time.split(":");
			return arr[0] * 60 + arr[1].substr(0, 2) * 1;
		}
	}

	function formatLyric(data) {
		var textArr = data.split("[");
		var arr = [];
		for(var i = 0; i < textArr.length; i++) {
			var lrcArr = textArr[i].split("]");
			//将时间转换成秒
			tranToSec(lrcArr[0], lrcArr[1]);
			if(typeof lrcArr[1] == "string") {
				if(!lrcArr[0] || lrcArr[1].length < 2) {
					continue;
				}
				arr.push({
					sec: tranToSec(lrcArr[0]),
					content: lrcArr[1]
				})
			}

		}
		return arr;
	}
	//设置下一曲，上一曲
	var songarr = {};

	function setMode(mode, $rootScope) {
		if($rootScope && $rootScope.playlist) {
			console.log($rootScope.playIndex);
			//顺序播放
			if(mode == 1) {
				if($rootScope.playmode == 1) {
					if($rootScope.playIndex < $rootScope.playlist.length - 1) {
						$rootScope.playIndex++;
					} else {
						mui.toast("已是最后一曲");
					}
				} else {
					if($rootScope.playIndex > 0) {
						$rootScope.playIndex--;
					} else {
						mui.toast("已是第一曲");
					}
				}
			//随机播放
			}else if(mode == 0){
				var a = $rootScope.playIndex;
				console.log(a,$rootScope.playIndex);
				$rootScope.playIndex = parseInt($rootScope.playlist.length * Math.random());
			}else{
			//单曲播放
			}
			$rootScope.song = $rootScope.playlist[$rootScope.playIndex];
			console.log(mode, console.log($rootScope.playIndex));
		} else {
			document.getElementById("audio").currentTime = 0;
			mui.toast("暂无其他音乐");
		}
	}
	var jq = window.jQuery;
	var windowHeight = jq(window).height();
	jq("body #keyWord").on("focus", function() {
		jq(".search-bg").css('height', windowHeight - 145);
	})
	angular.module('starter.controllers', [])
		.controller('AppCtrl', ["$scope", "$ionicModal", "$timeout", function($scope, $ionicModal, $timeout) {
			$scope.loginData = {};
			$scope.isLogin = true;
			$ionicModal.fromTemplateUrl('templates/login.html', {
				scope: $scope
			}).then(function(modal) {
				$scope.modal = modal;
			});
			//关闭登录模板
			$scope.closeLogin = function() {
				$scope.modal.hide();
			};
			// 打开登录模板
			$scope.login = function() {
				$scope.modal.show();
			};
			document.getElementById('audio').pause();
			// Perform the login action when the user submits the login form
			$scope.doLogin = function() {
				console.log('Doing login', $scope.loginData);
				if($scope.loginData.username == "xjy2016" && $scope.loginData.password == '11111111') {
					$timeout(function() {
						$scope.isLogin = false;
						$scope.closeLogin();
					}, 300);
				} else if($scope.loginData.username !== "xjy2016") {
					mui.toast("用户名错误");
				} else {
					mui.toast("密码错误");
				}

			};
		}])
		.controller("loginCtrl", ["$scope", function($scope) {

		}])
		.controller("searchCtrl", ["$scope", "playlist", "$rootScope", "$sce", function($scope, playlist, $rootScope, $sce) {
			$rootScope.historyList = $rootScope.historyList || [];
			$rootScope.sce = $sce.trustAsResourceUrl;
			$scope.playlistSearch = $scope.playlistSearch || [];
			$scope.searchSong = function() {
				var keyword = jq("#keyWord").val();
				playlist.searchSong(keyword);
			};
			$scope.$on("searchData", function(event, data) {
				$scope.playlistSearch = data;
				console.log($scope.playlistSearch);
			});
			$scope.mplay = function(i, song) {
				var songClone = JSON.parse(JSON.stringify(song));
				console.log(songClone);
				$rootScope.song = songClone;
				$rootScope.song.url = songClone.m4a;
			}
		}])
		//下面的播放器控制器
		.controller("myPlay", ["$scope", "$rootScope", "$sce", function($scope, $rootScope, $sce) {
			$rootScope.sce = $sce.trustAsResourceUrl;
			$scope.range = 0;
			$rootScope.song = $rootScope.song || {
				songname: "就算没有如果 (《三生三世十里桃花》电视剧插曲)",
				seconds: 305,
				albummid: "0011IIJE3XYf9L",
				songid: 200636355,
				singerid: 198,
				albumpic_big: "http://i.gtimg.cn/music/photo/mid_album_300/9/L/0011IIJE3XYf9L.jpg",
				albumpic_small: "http://i.gtimg.cn/music/photo/mid_album_90/9/L/0011IIJE3XYf9L.jpg",
				downUrl: "http://dl.stream.qqmusic.qq.com/200636355.mp3?vkey=A5745BAE81E140AE0451574187FBA448A947702B8B5703EC7853B9DCCD66040973CBE57E0EECBF69E5C0CBA581A74BFEB0036F1A67BE2AE5&guid=2718671044",
				url: "http://ws.stream.qqmusic.qq.com/200636355.m4a?fromtag=46",
				singername: "香香",
				albumid: 1853998
			};
			$rootScope.flag = true;
			var outrange = document.querySelector('.outrange');
			$rootScope.playIndex = $rootScope.playIndex || 1;
			var lineWidth = outrange.offsetWidth;
			audio.addEventListener("timeupdate", function() {
				var that = this;
				$scope.$apply(function() {
					$rootScope.currentTime = $scope.currentTime = parseInt(that.currentTime);
					$scope.range = that.currentTime / $rootScope.song.seconds * lineWidth;
					var elem = "body .time" + $scope.currentTime;
					var myLi = jq(elem).last();
					if(myLi.length > 0 && jq("#detailLrc li").length <= $rootScope.listLength) {
						myLi.addClass("active").siblings("li").removeClass("active");
						if(myLi.index() < 7) {
							myLi.parents(".lrcContent").css("transform", "translateY(0rem)");
						} else if(myLi.index() < 　($rootScope.listLength - 5)) {
							myLi.parents(".lrcContent").css("transform", "translateY(" + (-(myLi.index() - 5)) + "rem)");
						} else {
							myLi.parents(".lrcContent").css("transform", "translateY(" + (-($rootScope.listLength - 6)) + "rem)");
						}
					}
					if($scope.currentTime >= $rootScope.song.seconds) {
						myLi.parents(".lrcContent").css("transform", "translateY(0rem)")
						setMode(1, $rootScope);
					}
				})
			});
			//点击进度条设置时间
			var currWidth = jq("#rangeTime").outerWidth();
			var currLeft = jq("#rangeTime").offset().left;
			jq("#rangeTime").get(0).addEventListener("tap", function(e) {
				var currTime = e.detail.center.x - currLeft;
				document.getElementById("audio").currentTime = currTime / currWidth * $rootScope.song.seconds;
			})

			//点击播放暂停
			$scope.mPlay = function(e) {
				var audio = document.getElementById("audio");
				var outrange = document.getElementsByClassName("outrange")[0];
				if(audio) {
					if($rootScope.flag) {
						mui.toast("播放");
						audio.play();
						$rootScope.flag = false;
					} else {
						mui.toast("暂停");
						audio.pause();
						$rootScope.flag = true;
					}
				}
			}
			//function setMode( mode, $rootScope) {}
			//点击下一曲
			$scope.mNext = function() {
				$rootScope.playmode = "1"
				mui.toast("下一曲", 1500);
				$rootScope.flag = false;
				setMode($rootScope.myMode, $rootScope);
			}
			//点击上一曲
			$scope.mPrev = function() {
				$rootScope.playmode = "0"
				mui.toast("上一曲", 1500);
				$rootScope.flag = false;
				setMode($rootScope.myMode, $rootScope);
			}
			//设置播放模式
			$scope.isLoop = true;
			$scope.isMode = false;
			$scope.isSingle = false;
			$rootScope.myMode = 0;
			$scope.mMode = function() {
				var arr = ["随机播放", "顺序播放", "单曲循环"];
				$rootScope.myMode = ++$rootScope.myMode % 3;
				mui.toast(arr[$rootScope.myMode]);
				switch(Number($rootScope.myMode)) {
					case 0:
						$scope.isLoop = true;
						$scope.isMode = false;
						$scope.isSingle = false;
						$rootScope.myMode = 0;
						break;
					case 1:
						$scope.isLoop = false;
						$scope.isMode = true;
						$scope.isSingle = false;
						$rootScope.myMode = 1;
						break;
					case 2:
						$scope.isMode = false;
						$scope.isLoop = false;
						$scope.isSingle = true;
						$rootScope.myMode = 2;
						break;
					default:
						break;
				}
			}
		}])
		//播放列表控制器
		.controller('browserCtrl', ['$scope', '$rootScope', '$sce', function($scope, $rootScope, $sce) {
			if(localStorage.getItem("defaultlist"))
				$rootScope.defaultlist = JSON.parse(localStorage.getItem("defaultlist"));
			else
				$rootScope.defaultlist = {};
			$rootScope.playIndex = $rootScope.playIndex || 1;
			$rootScope.playlist = $rootScope.defaultlist || $rootScope.playlist;
			$rootScope.sce = $sce.trustAsResourceUrl;
			$scope.mplay = function(i, song) {
				console.log(i, song)
				$rootScope.song = song;
				console.log($rootScope.song);
				$rootScope.playIndex = i;
			}
		}])
		/*获取热门榜单*/
		.controller('PlaylistsCtrl', ["$scope", "playlists", "$ionicLoading", "$rootScope", function($scope, playlists, $ionicLoading, $rootScope) {
			//获取播放分类
			playlists.getId();
			$scope.$on("mytop", function(event, data) {
				$rootScope = $scope.playlists = data;
				$ionicLoading.hide();
			})
		}])
		/*获取音乐列表*/
		.controller('PlaylistCtrl', ["$scope", "$stateParams", "playlist", "$http", "$ionicLoading", "$sce", "$rootScope", function($scope, $stateParams, playlist, $http, $ionicLoading, $sce, $rootScope) {
			playlist.playlist($stateParams.playlistId);
			$scope.$on("playlist", function(event, data) {
				$scope.playlist = data;
				$rootScope.playlist = data;
				$ionicLoading.hide();
			})
			$scope.mplay = function(i, song) {
				var songClone = JSON.parse(JSON.stringify(song));
				$rootScope.sce = $sce.trustAsResourceUrl;
				$rootScope.song = songClone;
				localStorage.setItem("song", JSON.stringify(songClone));
			}
			if(localStorage.getItem("defaultlist"))
				$rootScope.defaultlist = JSON.parse(localStorage.getItem("defaultlist"));
			else
				$rootScope.defaultlist = [];
			var obj = {};
			angular.forEach($rootScope.defaultlist, function(val, i) {
				obj[val.songid] = true;
			})
			$scope.addplay = function(i, playlist) {
				var evt = window.event;
				evt.preventDefault();
				evt.stopPropagation();
				if(!obj[i]) {
					mui.toast(playlist.songname + "已添加进播放列表", 1500);
					$rootScope.defaultlist.push(playlist);
					localStorage.setItem("defaultlist", JSON.stringify($rootScope.defaultlist));
					console.log(JSON.parse(localStorage.getItem("defaultlist")))
					obj[i] = true;
				} else {
					mui.toast(playlist.songname + "已存在播放列表", 1500);
				}
				console.log($rootScope.defaultlist);
			}
			$rootScope.$watch('song', function(newValue, oldValue) {

			})
		}])
		//歌词控制器
		.controller('PlaylistDetailCtrl', ["$scope", "$rootScope", 'playlist', function($scope, $rootScope, playlist) {
			$scope.volume = document.getElementById("audio").volume * 100;
			console.log(document.getElementById("audio").volume)
			$scope.$on("mlyric", function(event, data) {
				data = HtmlDecode(data);
				$scope.list = formatLyric(data);
				$rootScope.listLength = $scope.list.length;
			})
			//监听音乐的变换
			$rootScope.$watch('song', function(newValue, oldValue) {
				$rootScope.flag = false;
				playlist.getLrc($rootScope.song.songid);
			});
			$scope.voiceReduce = function() {
				if(document.getElementById("audio").volume > 0) {
					document.getElementById("audio").volume -= 0.1;
					$scope.volume = document.getElementById("audio").volume * 100;
					console.log($scope.volume);
				}
			};
			$scope.voiceAdd = function() {
				console.log(document.getElementById("audio"));
				if(document.getElementById("audio").volume < 1) {
					document.getElementById("audio").volume += 0.1;
					$scope.volume = document.getElementById("audio").volume * 100;
					console.log($scope.volume);
				}
			}

		}])
		//将0秒时间转换成 0:00 格式
		.filter('timeFormat', function() {
			return function(time) {
				if(typeof time === "number") {
					var minutes = parseInt(time / 60) + "";
					var seconds = time % 60 < 10 ? ("0" + time % 60) : ("" + time % 60);
					return minutes + ":" + seconds;
				} else {
					return "0:00";
				}
			}
		})
		//搜索关键词高亮
		.filter('searchLight', function() {
			return function(str) {
				if(jq("#keyWord").val()) {
					str = str.replace(jq("#keyWord").val(), "<b>" + jq("#keyWord").val() + "</b>");
					return str;
				} else {
					return str;
				}
			}
		}).filter('searchFormat', function() {
			return function(str) {
				if(str) {
					str = str.substr(-3, str.length);
					return str;
				}
			}
		});
}